package Server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.util.ArrayList;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import Agent.Agent;
import Agent.ObjectAgent;
import SLA.SLA;
import Session.Session;

public class Server {
	

	private static final Logger LOG = Logger.getLogger(Server.class.getName());
	
	public Server() throws SecurityException, IOException {
		
		Handler file = new FileHandler("Logger.txt");
		file.setLevel(Level.ALL);
		LOG.addHandler(file);
		LOG.setUseParentHandlers(false);
	}
	    
	public void dispatchQuery(String inputPath, ArrayList<String> queries,int numAgents) throws NumberFormatException, NotBoundException, IOException{
		
		Remote obj = null;
		String[] s;
		ObjectAgent objAgent = null;
		String[] informationAgent;
        BufferedReader in = new BufferedReader(new FileReader(inputPath));
        String str;
        ArrayList<String> transaction = new ArrayList<String>();
        int fromIndex=0;
        int length = queries.size()/numAgents;
        int toIndex = fromIndex + length;
        
        int agents = numAgents;
        
        
        while (in.ready()){
        	if((str = in.readLine())!=null){
        		System.out.println(str);
        		
        		if(str.startsWith("agent")){
        			informationAgent = str.substring(6).split(" ");
        			System.out.println("AGENTE:"+informationAgent[0]+" "+informationAgent[1]+" "+informationAgent[2]);
        			objAgent = new ObjectAgent(Integer.parseInt(informationAgent[1]),informationAgent[0],informationAgent[2]);
        			obj = LocateRegistry.getRegistry(informationAgent[0],Integer.parseInt(informationAgent[1])).lookup(informationAgent[2]);
        			agents--;
        			if(agents==0) toIndex = queries.size();
        			transaction.addAll(queries.subList(fromIndex, toIndex));
        			
        			fromIndex=toIndex;
        			if(length+fromIndex>queries.size()) toIndex=queries.size();
        			else toIndex+=length;
        			
		  		}
        		else if(str.startsWith("sla")){
        			s = str.substring(4).split(" ");
        			SLA sla = new SLA(new Float(s[0]), new Float(s[1]),Integer.parseInt(s[2]), new Float(s[3]), new Float(s[4]),new Float(s[5]),new Float(s[6]),
        						new Float(s[7]));
        			((Agent) obj).setSla(sla);
        		
        			Session sessionClient = new Session(this);
        			sessionClient.addAgent(objAgent);
        			((Agent) obj).addTransaction(transaction);
        			transaction = new ArrayList<String>();
        			new Thread(sessionClient).start();
        		}
        	}
        }
        in.close();
	}

}